//
//  LBDropDownMenu.m
//  LBWeibo
//
//  Created by 卢玉强 on 16/3/9.
//  Copyright © 2016年 Label. All rights reserved.
//

#import "LBDropDownMenu.h"

@interface LBDropDownMenu ()
// 内容视图强引用；
@property (strong, nonatomic) UIView *contentView;
// 内容视图控制器强引用；
@property (strong, nonatomic) UIViewController *contentViewController;
// 容器视图强引用
@property (strong, nonatomic) UIImageView *containerView;
@end

@implementation LBDropDownMenu

/** 初始化视图;
 */
- (instancetype)initWithFrame:(CGRect)frame {
        if ( self = [super initWithFrame:frame] ) {
                [self setFrame:[[UIScreen mainScreen] bounds]];
                [self addSubview:self.containerView];
                [self setBackgroundColor:[UIColor clearColor]];
        }
        return self;
}

/** 添加子视图;
 */
- (void)addContentView:(UIView *)contentView {
        // 微调布局－contentView坐标；
        contentView.origin = CGPointMake(6, 11);
        // 微调布局－containerView高度；
        self.containerView.height = 11 + contentView.height + 8;
        // 微调布局－contentView宽度；
        contentView.width = self.containerView.width - 6 - 6;
        // 微调布局－获取强引用；
        self.contentView = contentView;
        // 微调布局－添加contentView；
        [self.containerView addSubview:contentView];
}

/** 添加子视图控制器;
 */
- (void)addContentViewController:(UIViewController *)contentViewController {
        // 微调布局－contentView坐标；
        contentViewController.view.origin = CGPointMake(6, 11);
        // 微调布局－containerView高度；
        self.containerView.height = 11 + contentViewController.view.height + 8;
        // 微调布局－contentView宽度；
        contentViewController.view.width = self.containerView.width - 6 - 6;
        // 微调布局－获取强引用；
        self.contentViewController = contentViewController;
        // 微调布局－添加contentView；
        [self.containerView addSubview:self.contentViewController.view];
}

/** 显示视图;
 */
- (void)showFrom:(UIView *)sender {
        // 1. 获取顶层窗口；
        UIWindow *window = [[[UIApplication sharedApplication] windows] lastObject];
        // 2. 获取控件的绝对坐标；
        // CGRect frame = [sender.superview convertRect:sender.frame toView:window];
        CGRect absoluteFrame = [sender convertRect:sender.bounds toView:window];
        // 3. 设置下拉窗口的坐标；
        self.containerView.centerX = CGRectGetMidX(absoluteFrame);
        self.containerView.y = CGRectGetMaxY(absoluteFrame);
        // 4. 显示下拉窗口；
        [window addSubview:self];
}

/** 根据背景图片创建containerView；
 */
- (UIImageView *)containerView {
        if (!_containerView) {
                _containerView =  [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"popover_background"]];
                [_containerView setUserInteractionEnabled:YES];
        }
        return _containerView;
}

/** 隐藏窗口－函数调用；
 */
-(void)dismiss {
        [self removeFromSuperview];
}

/** 隐藏窗口－按钮事件；
 */
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
        [self dismiss];
}
@end
